﻿layui.use(function () {
    var $ = layui.$;
    var layer = layui.layer;
    var util = layui.util;
    var form = layui.form;
    var table = layui.table;
    let selected = [];
    let selectedRows = [];
    var datasadd = [];
    var token = localStorage.getItem("token");
    // 新库位
    let movelocationlist = {
        3: '默认报损库位',
        4: '报损库位',
        5: '报损库位',
        6: '报损库位',
        7: '报损仓库',
        8: '报损库位',
        9: '默认库位',
        11: '默认新增库位',
        24: '新品仓库',
        41: '废品库位',
        42: '废品仓库'
    };
    // 事件
    util.on('lay-on', {
        //新增产品
        'test-page': function () {

            //创建弹出层
            var index = layer.open({
                type: 1,
                area: ['1300px', '500px'], // 宽高
                content: '<form class="layui-form layui-row layui-col-space16" id="IDProdurement">' +
                    '<div class="layui-col-md4">' +
                    '<label class="layui-form-label" style="width: 120px" >产品编码:</label>' +
                    '<div class="layui-input-block">' +
                    '<input type="text" id="productsCode" placeholder="产品编码" style="width:200px;" class="layui-input" lay-affix="clear">' +
                    '</div>' +
                    '</div>' +
                    '<div class="layui-col-md4">' +
                    '<label class="layui-form-label" style="width: 120px">产品名称:</label>' +
                    '<div class="layui-input-block">' +
                    '<input type="text" name="B" placeholder="产品名称" id="productsName" style="width:200px;" lay- affix="clear" class= "layui-input">' +
                    '</div>' +
                    '</div>' +
                    '<div class="layui-btn-container layui-col-md4">' +
                    '<button type="button" class="layui-btn" id="searchBtn" > 查询</button>' +
                    '</div> ' +
                    '</form>' +
                    '<table class= "layui-table" id="Produrement-Id" >' +
                    '<thead>' +
                    '<tr>' +
                    '<th lay-data="{checkbox:true}" rowspan="2"></th>' +
                    '<col width="150">' +
                    '<col>' +
                    '</tr>' +
                    '</thead>' +
                    '</table>' +
                    '<button type="button" id="demo-login" class="layui-btn layui-bg-blue">提交</button>'
            });
            //弹出层弹出时显示数据
            getProcurementList({
                productsCode: null,
                productsName: null,
                pageIndex: 1,
                pageSize: 4
            });
            //查询
            $("#searchBtn").on('click', function () {
                var productsCode = $("#productsCode").val();
                var productsName = $("#productsName").val();
                getProcurementList({
                    productsCode: productsCode,
                    productsName: productsName,
                    pageIndex: 1,
                    pageSize: 4
                });
            });
            //获取复选框的值
            table.on('checkbox(Produrement-Id)', function (obj) {
                console.log(obj);
                // 当前选中的行加入到 selectedRows 数组中
                if (obj.checked) {
                    selectedRows.push(obj.data);
                }
                else {
                    // 当前取消选中的行从 selectedRows 数组中移除
                    selectedRows = selectedRows.filter(row => row.productsID !== obj.data.productsID);
                }
                console.log(selectedRows)
            })
            //显示选中的产品信息(点击提交)
            $("#demo-login").on('click', function () {
                //关闭弹出层
                layer.close(index);
                var objs = {
                    Token: token,
                    pageIndex: 1,
                    pageSize: 1000,
                    StoreCode: '',
                    StoreName: '',
                    wid: ''
                }
                $.ajax({
                    url: "/Foundation/GetStorehouse",
                    type: "get",
                    data: objs,
                    success: function (d) {
                        var res = JSON.parse(d);
                        var supper = res.data.list;
                        console.log(supper);
                        var options = '<option value="">请选择库位</option>';
                        supper.forEach(function (item) {
                            options += '<option value="' + item.storehouseId + '">' + item.storehouseName + '</option>';
                        });
                        $('.city').html(options);
                        form.render('select');
                    },
                    error: function (xhr, status, error) {
                        console.log("新增出错: " + error);
                    }
                });
                //关闭弹出层
                layer.close(index);
                //显示选中的产品
                table.render({
                    elem: "#ID-demo",
                    css: [
                        // 设置单元格样式
                        // 取消默认的溢出隐藏，并设置适当高度
                        '.layui-table-cell{height: 50px; line-height: 40px;}',
                        '.layui-table-cell .layui-colorpicker{width: 38px; height: 38px;}',
                        '.layui-table-cell select{height: 36px; padding: 0 5px;}',
                    ].join(''),
                    cols: [[
                        { type: 'checkbox' },
                        { field: 'productsName', title: '产品名称', width: 200 },
                        { field: 'productsCode', title: '产品编码', width: 200 },
                        { field: 'specs', title: '规格', width: 150 },
                        { field: 'price', title: '单价', width: 150 },
                        {
                            field: 'moveProductNum',
                            title: '数量',
                            width: 150,
                            edit: 'text'
                        },
                        {
                            field: 'storehouseId', title: '当前库位', width: 150,
                            templet: function (d) {
                                return movelocationlist[d.storehouseId];
                            }
                        },
                        {
                            field: 'movelocation', title: '库位', minWidth: 120, templet: '#TPL-select'
                        },
                    ]],
                    data: selectedRows,
                    loading: true,

                    done: function (res, curr, count) {
                        var options = this;
                        table.on('edit(ID-demo)', function (obj) {
                            var value = obj.value; // 得到修改后的值
                            var data = obj.data; // 得到所在行所有键值
                            console.log(data);
                            var field = obj.field; // 得到字段
                        });

                        form.on('select(select-demo)', function (obj) {
                            selectedvalue = obj.value; // 获取选中项 value
                            table.on('checkbox(ID-demo)', function (obj) {
                                //当前选中的行加入到 selected 数组中
                                if (obj.checked) {
                                    var a = {
                                        "addName": "string",
                                        "addTime": "2024-12-02T06:04:18.564Z",
                                        "updName": "string",
                                        "updTime": "2024-12-02T06:04:18.564Z",
                                        "delName": "string",
                                        "delTime": "2024-12-02T06:04:18.564Z",
                                        "isDel": false,
                                        "movelibraryCode": obj.data.movelibraryCode,
                                        "productsID": obj.data.productsID,
                                        "moveProductNum": obj.data.moveProductNum,
                                        "movelocation": selectedvalue,
                                        "office_id": "string",
                                        "user_id": 0,
                                    };
                                    datasadd.push(a);
                                }
                                else {
                                    // 当前取消选中的行从 selected 数组中移除
                                    selected = selected.filter(row => row.productsID !== obj.data.productsID);
                                }
                                console.log(selected)
                            })
                        });
                        //获取复选框的值

                    }
                });
            })
        }
    });
    //显示+查询
    function getProcurementList({ productsCode, productsName, pageIndex = 1, pageSize = 4 }) {
        var obj = {
            Token: token,
            pindex: pageIndex,
            psize: pageSize,
            productsCode: productsCode,
            productsName: productsName
        }
        $.ajax({
            url: "/Procurement/GetProductList",
            type: "get",
            data: obj,
            success: function (d) {
                var res = JSON.parse(d);
                if (res != null && res.data) {
                    // 渲染表格
                    table.render({
                        elem: '#Produrement-Id',
                        cols: [[
                            { type: 'checkbox', fixed: 'left' },
                            { field: 'productsCode', title: '产品编码', width: 200, fixed: 'left', unresize: true },
                            { field: 'productsName', title: '产品名称', width: 200 },
                            { field: 'specs', title: '规格', width: 150 },
                            { field: 'productTypeID', title: '类别', width: 150 },
                            { field: 'storageUnits', title: '存储单位', width: 150 },
                            { field: 'wrapType', title: '包装类型', width: 150 },
                            { field: 'price', title: '单价', width: 150 },
                            { field: 'weight', title: '重量', width: 150 }
                        ]],
                        data: res.data.list,  // 数据源
                        page: true,   // 启用分页
                        limit: pageSize,    // 每页显示多少条数据
                        limits: [10, 20, 30],  // 分页选择项
                        total: res.data.lcount,  // 总记录数
                        loading: true // 启用加载状态
                    });

                    // 渲染分页控件
                    layui.laypage.render({
                        elem: 'pagination',  // 分页容器
                        count: res.data.lcount,  // 总记录数
                        limit: pageSize,
                        jump: function (obj, first) {
                            if (!first) {
                                fetchProductList({ productsCode, productsName, pageIndex: obj.curr, pageSize });  // 翻页时重新请求数据
                            }
                        }
                    });
                }
            },
            error: function (xhr, status, error) {
                console.log("查询出错: " + error);
            }
        });
    }
    //点击提交添加
    var code = Math.floor(Math.random() * 1000000) + 100000;
    $("#MovelibraryCode").val(code)
    var zhidanren = "呓语";
    $("#MakePerson").val(zhidanren)
    var date = new Date();
    // 获取年、月、日
    var year = date.getFullYear();
    var month = (date.getMonth() + 1).toString().padStart(2, '0');  // 月份从0开始，因此加1
    var day = date.getDate().toString().padStart(2, '0');  // 补充两位数字

    // 拼接成 "yyyy-MM-dd" 格式
    var formattedDate = `${year}-${month}-${day}`;
    $("#MarkTime").val(formattedDate)
    //点击提交添加
    $("#addpro").on('click', function () {
        let obj = {
            MovelibraryCode: $("#MovelibraryCode").val(),
            MovelibraryType: $("#MovelibraryType").val(),
            MorderNumber: $("#MorderNumber").val(),
            MakePerson: $("#MakePerson").val(),
            MarkTime: $("#MarkTime").val(),
            ORremark: $("#ORremark").val(),
            ReasonForReview: 1,
            DocumentStatus: 1,
            IsRemoved: false,
            office_id: "1859803506630856704",
            user_id: 3,
            AllProducs: datasadd,
            Token: token
        }
        console.log(obj);
        $.ajax({
            url: "/Movelibrary/AddMovelibrarys",
            type: "post",
            data: obj,
            success: function (d) {
                var s = JSON.parse(d)
                if (s.data > 0) {
                    layer.msg('添加成功', { icon: 1 }, function () {
                        location.href = '/Movelibrary/ShowMovelibrary';
                    });
                }
                else {
                    layer.msg('添加失败');
                    return
                }
            }
        })
    })
})